<template>
  <div
    class="video-inside-view"
    ref="videoInsideView"
    v-if="contentData.length > 0"
  >
    <div class="content-wrap" ref="contentWrap">
      <div
        class="content-box"
        ref="contentBox"
        v-for="(item, index) in contentData"
        :key="item.id"
      >
        <div>
          <div class="bg-0"></div>
          <div
            class="bg"
            @touchstart.self="showMenu(item, index, $event)"
            @touchmove="videoChangeMove(index, $event)"
            @touchend="videoChangeEnd(index, $event)"
          >
            >
            <div class="bg-bottom" v-if="item.isShowMenu"></div>
          </div>
          <div class="top-nav">
            <div class="goback-icon" @click="goBack">
              <van-icon name="arrow-left" />
            </div>
            <div class="user-msg">
              <div class="imgbox">
                <img class="auto-img" :src="item.user.thumb" alt="" />
              </div>
              <div class="textbox">
                <div class="top">{{ item.user.login }}</div>
                <div class="bottom">
                  {{
                    item.loop > 10000
                      ? `${Math.floor(item.loop / 10000)}+万`
                      : item.loop
                  }}
                  次播放
                </div>
              </div>
            </div>
            <div class="follow-icon" @click="toFollow(item)">
              {{ item.isFollow == true ? "已关注" : "关注" }}
            </div>
          </div>
          <div class="video-box" v-if="item.format == 'video'">
            <video
              ref="video"
              muted
              :src="item.high_url"
              autoplay
              @canplay="videoPlayHandel(item, index)"
              @timeupdate="videoPlayingHandel(item, index)"
            ></video>
          </div>
          <div class="bottom-menu" v-show="item.isShowMenu">
            <div class="title">{{ item.content }}</div>
            <div class="bottom-icon">
              <div class="bottom-icon-left">
                <div
                  class="icon like"
                  :class="{ likeActive: item.isLike }"
                  @click="toLike(item)"
                >
                  <div class="like-count">{{ item.votes.up }}</div>
                </div>
                <div
                  class="icon dislike"
                  :class="{ dislikeActive: item.isDislike }"
                  @click="toDislike(item)"
                ></div>
              </div>
              <div class="bottom-icon-right">
                <div class="icon comment" @click="goToComment(item)">
                  <div class="comment-count">
                    {{ item.comments_count > 0 ? item.comments_count : "评论" }}
                  </div>
                </div>
                <div
                  class="icon share"
                  @click="(showShare = true), shareHandel(item)"
                >
                  <div class="share-count">
                    {{ item.share_count > 0 ? item.share_count : "分享" }}
                  </div>
                </div>
              </div>
            </div>
            <div class="play-control">
              <div class="play-btn" @click="playAndPause(item, index)">
                <van-icon :name="item.isPlay == true ? 'pause' : 'play'" />
              </div>
              <div class="current-time">{{ item.currentTime }}</div>
              <div class="progress" ref="progress">
                <div
                  class="layer"
                  @click.stop="changeTime(item, index, $event)"
                  @touchmove="dragToChangeTimeData(item, index, $event)"
                  @touchend="dragToChangeTime(item, index, $event)"
                ></div>
                <div
                  class="progress-btn"
                  :style="{ left: item.left - 4 + '%' }"
                ></div>
                <div
                  class="progress-bar"
                  :style="{ width: item.left + '%' }"
                ></div>
              </div>
              <div class="total-time">{{ item.totalTime }}</div>
            </div>
          </div>
          <van-share-sheet
            v-model:show="showShare"
            title="立即分享给好友"
            :options="options"
            @select="onSelect"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref } from "vue";
import { Toast } from "vant";
import { getHomeCommendContent } from "../../api/home";

export default {
  setup() {
    const showShare = ref(false);
    const options = [
      { name: "微信", icon: "wechat" },
      { name: "微博", icon: "weibo" },
      { name: "复制链接", icon: "link" },
      { name: "分享海报", icon: "poster" },
      { name: "二维码", icon: "qrcode" },
    ];

    const onSelect = (option) => {
      Toast(option.name);
      showShare.value = false;
    };

    return {
      options,
      onSelect,
      showShare,
    };
  },
  name: "VideoInside",
  data() {
    return {
      contentData: [],
      videoChangeY: 0,
      videoChangeTotalHeight: 0,
      loading: true,
      activeIndex: 0,
      timer: null,
    };
  },
  watch: {},
  created() {
    // this.contentData = JSON.parse(
    //   window.localStorage.getItem("VideoContentData")
    // );
  },
  activated() {
    this.contentData = JSON.parse(
      window.localStorage.getItem("VideoContentData")
    );
    this.$forceUpdate();
    this.activeIndex = this.$route.params.index;
    this.timer = setTimeout(() => {
      this.videoChangeTotalHeight =
        this.$refs.contentBox[0].clientHeight * this.activeIndex;
      this.$refs.contentWrap.style.transition = "none";
      this.$refs.contentWrap.style.transform = `translateY(-${this.videoChangeTotalHeight}px)`;
      this.$refs.video[this.activeIndex].play();
      this.videoPlayHandel(
        this.contentData[this.activeIndex],
        this.activeIndex
      );
      this.timer = null;
      //定时器延迟拿取数据
      this.timer = setTimeout(() => {
        this.getFollowedData();
        this.timer = null;
      }, 100);
    }, 100);
  },
  methods: {
    //关注
    toFollow(item) {
      let token = window.localStorage.getItem("token");
      if (!token) {
        this.$router.push({ name: "beforeLogin" });
      } else {
        item.isFollow = !item.isFollow;
        let followedData = JSON.parse(
          window.localStorage.getItem("followedData")
        );
        let idArr = [];
        followedData.forEach((item) => {
          idArr.push(item.id);
        });
        if (item.isFollow && idArr.indexOf(item.user.id) == -1) {
          followedData.push(item.user);
          window.localStorage.setItem(
            "followedData",
            JSON.stringify(followedData)
          );
        } else {
          // console.log(followedData.indexOf(item.user));
          followedData.forEach((item2, index) => {
            if (item2.id == item.user.id) {
              followedData.splice(index, 1);
              window.localStorage.setItem(
                "followedData",
                JSON.stringify(followedData)
              );
            }
          });
        }
      }
      window.localStorage.setItem(
        "VideoContentData",
        JSON.stringify(this.contentData)
      );
    },
    //点赞
    toLike(item) {
      item.isLike = !item.isLike;
      if (item.isLike) {
        item.isDislike = false;
        item.votes.up++;
      } else {
        item.votes.up--;
      }
      window.localStorage.setItem(
        "VideoContentData",
        JSON.stringify(this.contentData)
      );
    },
    //踩
    toDislike(item) {
      item.isDislike = !item.isDislike;
      if (item.isDislike && item.isLike) {
        item.isLike = false;
        item.votes.up--;
      }
      window.localStorage.setItem(
        "VideoContentData",
        JSON.stringify(this.contentData)
      );
    },
    //分享
    shareHandel(item) {
      item.share_count++;
      window.localStorage.setItem(
        "VideoContentData",
        JSON.stringify(this.contentData)
      );
    },
    //返回上一级路由
    goBack() {
      this.$router.go(-1);
    },
    //跳转评论详情页
    goToComment(item) {
      window.localStorage.setItem("commentContentData", JSON.stringify(item));
      let dataId = item.id;
      if (dataId != 125654473 && dataId != 125657703) {
        dataId = 125654473;
      }
      this.$router.push(`/comment?id=${dataId}`);
    },
    //初始化视频时间
    videoPlayHandel(item, index) {
      let totalMinutes = Math.floor(this.$refs.video[index].duration / 60);
      totalMinutes = totalMinutes >= 10 ? totalMinutes : "0" + totalMinutes;
      let totalSeconds = Math.floor(this.$refs.video[index].duration % 60);
      totalSeconds = totalSeconds >= 10 ? totalSeconds : "0" + totalSeconds;
      item.totalTime = `${totalMinutes}:${totalSeconds}`;
      item.isPlay = true;
      item.currentTime = `00:00`;
      item["isShowMenu"] = false;
      this.$forceUpdate();
    },
    //视频播放时实时更新数据
    videoPlayingHandel(item, index) {
      let currentMinutes = Math.floor(this.$refs.video[index].currentTime / 60);
      currentMinutes =
        currentMinutes >= 10 ? currentMinutes : "0" + currentMinutes;
      let currentSeconds = Math.floor(this.$refs.video[index].currentTime % 60);
      currentSeconds =
        currentSeconds >= 10 ? currentSeconds : "0" + currentSeconds;
      item.currentTime = `${currentMinutes}:${currentSeconds}`;
      item.left =
        (this.$refs.video[index].currentTime /
          this.$refs.video[index].duration) *
        100;
      if (item.currentTime == item.totalTime) {
        item.isPlay = false;
        this.$forceUpdate();
      }
      this.$forceUpdate();
    },
    //控制底部菜单的显示隐藏
    showMenu(item, index, e) {
      item.isShowMenu = !item.isShowMenu;
      this.videoChangeY = e.changedTouches[0].pageY;
      this.addHistoryData(index);
      this.$forceUpdate();
    },
    //暂停与播放
    playAndPause(item, index) {
      item.isPlay = !item.isPlay;
      this.$forceUpdate();
      if (item.isPlay) {
        this.$refs.video[index].play();
      } else if (!item.isPlay) {
        this.$refs.video[index].pause();
      }
    },
    //点击切换进度
    changeTime(item, index, e) {
      this.$refs.video[index].currentTime =
        (e.offsetX / this.$refs.progress[index].clientWidth) *
        this.$refs.video[index].duration;
      item.isPlay = true;
      this.$refs.video[index].play();
      this.$forceUpdate();
    },
    //拖动进度条切换进度(move事件)
    dragToChangeTimeData(item, index, e) {
      if (item.currentTime == item.totalTime) {
        item.currentTime = item.totalTime;
      }
      item.isPlay = false;
      this.$refs.video[index].pause();
      //视频总时长
      let eT = this.$refs.video[index].duration;
      //坐标
      let eX = e.changedTouches[0].pageX - 95;
      //进度条宽度
      let eW = this.$refs.progress[index].clientWidth;
      //限制移动范围
      eX = eX > eW ? eW : eX < 0 ? 0 : eX;
      //进度条与按钮移动比率
      let present = eX / eW;
      //进度条与按钮移动百分比
      let left = present * 100;
      left = left < 0 ? 0 : left > 100 ? 100 : left;
      item.left = left;
      let currentMinutes = Math.floor(Math.floor(present * eT) / 60);
      currentMinutes =
        currentMinutes >= 10 ? currentMinutes : "0" + currentMinutes;
      let currentSeconds = Math.floor(present * eT) % 60;
      currentSeconds =
        currentSeconds >= 10 ? currentSeconds : "0" + currentSeconds;
      item.currentTime = `${currentMinutes}:${currentSeconds}`;
      item.isPlay = true;
      this.$forceUpdate();
    },
    //拖动进度条切换进度(end事件)
    dragToChangeTime(item, index, e) {
      let present =
        (e.changedTouches[0].pageX - 95) /
        this.$refs.progress[index].clientWidth;
      this.$refs.video[index].currentTime =
        present * this.$refs.video[index].duration;
      item.isPlay = true;
      this.$refs.video[index].play();
      this.$forceUpdate();
    },
    videoChangeMove(index, e) {
      if (e.changedTouches[0].pageY < this.videoChangeY) {
        if (this.contentData.length - 1 == index) {
          this.$toast("没有更多了哦~");
          return;
        }
        this.$refs.contentWrap.style.transform = `translateY(-${
          this.videoChangeY -
          e.changedTouches[0].pageY +
          index * this.$refs.contentBox[index].clientHeight
        }px)`;
      } else if (e.changedTouches[0].pageY > this.videoChangeY) {
        this.$refs.contentWrap.style.transform = `translateY(-${
          index * this.$refs.contentBox[index].clientHeight -
          (e.changedTouches[0].pageY - this.videoChangeY)
        }px)`;
      }
    },
    //滑动切换视频(end)
    videoChangeEnd(index, e) {
      this.addHistoryData(index);
      let present = this.$refs.contentBox[index].clientHeight / 3;
      this.$refs.contentWrap.style.transition = "all linear 0.5s";
      if (
        e.changedTouches[0].pageY < this.videoChangeY &&
        this.videoChangeY - e.changedTouches[0].pageY >= present
      ) {
        if (this.contentData.length - 1 == index) {
          if (this.loading) {
            this.getHomeCommendContentData(0);
          } else if (!this.loading) {
            this.$toast("没有更多了哦~");
            return;
          }
        }
        this.videoChangeTotalHeight +=
          this.$refs.contentBox[index].clientHeight;
        this.$refs.contentWrap.style.transform = `translateY(-${this.videoChangeTotalHeight}px)`;
        this.activeIndex++;
        this.$refs.video[this.activeIndex].play();
        this.videoPlayHandel(
          this.contentData[this.activeIndex],
          this.activeIndex
        );
      } else {
        this.$refs.contentWrap.style.transform = `translateY(-${this.videoChangeTotalHeight}px)`;
      }
      if (
        e.changedTouches[0].pageY > this.videoChangeY &&
        e.changedTouches[0].pageY - this.videoChangeY >= present
      ) {
        if (index == 0) {
          this.$toast("没有更多了哦~");
          return;
        }
        this.videoChangeTotalHeight -=
          this.$refs.contentBox[index].clientHeight;
        this.$refs.contentWrap.style.transform = `translateY(-${this.videoChangeTotalHeight}px)`;
        this.activeIndex--;
        this.$refs.video[this.activeIndex].play();
        this.videoPlayHandel(
          this.contentData[this.activeIndex],
          this.activeIndex
        );
      } else {
        this.$refs.contentWrap.style.transform = `translateY(-${this.videoChangeTotalHeight}px)`;
      }
    },
    //获取已关注
    getFollowedData() {
      let followedData = JSON.parse(
        window.localStorage.getItem("followedData")
      );
      let followedDataId = [];
      followedData.forEach((item) => {
        followedDataId.push(item.id);
      });
      this.contentData.forEach((item) => {
        if (followedDataId.indexOf(item.user.id) != -1) {
          item.isFollow = true;
        } else {
          item.isFollow = false;
        }
      });
    },
    //添加历史观看数据
    addHistoryData(index) {
      let historyData = JSON.parse(window.localStorage.getItem("historyData"));
      if (!historyData) {
        let historyData = [];
        historyData.unshift(this.contentData[index]);
        window.localStorage.setItem("historyData", JSON.stringify(historyData));
      } else {
        let idArr = [];
        historyData.forEach((item) => {
          if (idArr.indexOf(item.id) == -1) {
            idArr.push(item.id);
          }
        });
        if (idArr.indexOf(this.contentData[index].id) == -1) {
          historyData.unshift(this.contentData[index]);
          window.localStorage.setItem(
            "historyData",
            JSON.stringify(historyData)
          );
        }
      }
    },
    async getHomeCommendContentData(dataParams) {
      await getHomeCommendContent({ axios: this.$axios }, dataParams).then(
        ({ data }) => {
          data.items.forEach((item) => {
            item["isAutoplay"] = false;
            item["isFollow"] = false;
            item["isLike"] = false;
            item["isDislike"] = false;
          });
          let res = data.items.filter((item) => {
            return item.format == "video";
          });
          this.contentData.push(...res);
          this.timer = setTimeout(() => {
            this.loading = false;
            this.timer=null
          }, 100);
          // console.log(this.contentData);
        }
      );
    },
  },
};
</script>

<style lang="scss" scoped>
.video-inside-view {
  width: 100vw;
  height: 100vh;
  box-sizing: border-box;
  overflow: hidden;
  color: #fff;
  position: relative;
  .content-wrap {
    transition: all linear 0.5s;
    .content-box {
      width: 100vw;
      height: 100vh;
      position: relative;
      top: 0px;
      left: 0px;
      z-index: 9999;
      background-color: #fff;
      .bg-0 {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: rgb(0, 0, 0);
        z-index: 0;
      }
      .bg {
        // height: 50px;
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: rgba(0, 0, 0, 0.15);
        z-index: 2;
        .bg-bottom {
          position: absolute;
          bottom: 0;
          left: 0;
          right: 0;
          height: 50px;
          background-color: rgba(0, 0, 0, 0.35);
        }
      }
      .top-nav {
        width: 100%;
        height: 50px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        position: absolute;
        top: 10px;
        left: 0;
        padding: 10px;
        box-sizing: border-box;
        z-index: 10;
        .goback-icon {
          font-size: 25px;
        }
        .user-msg {
          display: flex;
          .imgbox {
            width: 35px;
            height: 35px;
            border-radius: 999px;
            overflow: hidden;
          }
          .textbox {
            line-height: 17px;
            margin-left: 10px;
          }
        }
        .follow-icon {
          width: 50px;
          height: 22px;
          flex: 0 0 50px;
          border-radius: 999px;
          text-align: center;
          background-color: rgba(255, 255, 255, 0.715);
          line-height: 22px;
          font-weight: 600;
          margin-left: -10px;
          color: black;
        }
      }
      .video-box {
        width: 100vw;
        height: 100vh;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        video {
          width: 100%;
          height: 100%;
          position: absolute;
          top: 0;
          bottom: 0;
          left: 0;
          right: 0;
          margin: auto;
          z-index: 1;
        }
      }
      .title {
        color: #fff;
        position: absolute;
        bottom: 60px;
        left: 20px;
        z-index: 8;
        width: calc(100% - 20px);
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        font-size: 15px;
      }
      .bottom-icon {
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin: 10px auto 0;
        padding: 10px 0 10px 10px;
        box-sizing: border-box;
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        z-index: 10;
        .bottom-icon-left {
          display: flex;
          justify-content: space-between;
          align-items: center;
          .icon {
            width: 35px;
            height: 35px;
            border-radius: 999px;
            background-repeat: no-repeat;
            background-position: center center;
            background-size: cover;
            position: relative;
            &.like {
              margin-right: 30px;
              background-image: url(@/assets/images/home/yH1.png);
              &.likeActive {
                background-image: url(@/assets/images/home/utK.png);
              }
              .like-count {
                position: absolute;
                font-size: 12px;
                left: 35px;
                top: 12px;
                font-weight: 600;
              }
            }
            &.dislike {
              background-image: url(@/assets/images/home/xKl.png);
              &.dislikeActive {
                background-image: url(@/assets/images/home/Dfk.png);
              }
            }
          }
        }
        .bottom-icon-right {
          display: flex;
          justify-content: space-between;
          align-items: center;
          flex: 0 0 120px;
          .icon {
            width: 35px;
            height: 35px;
            border-radius: 999px;
            background-repeat: no-repeat;
            background-position: center center;
            background-size: cover;
            position: relative;
            &.comment {
              margin-right: 30px;
              background-image: url(@/assets/images/home/u0q2.png);
              .comment-count {
                position: absolute;
                font-size: 12px;
                left: 35px;
                top: 12px;
                font-weight: 600;
                height: 12px;
                flex: 0 0 26px;
                width: 26px;
              }
            }
            &.share {
              margin-right: 30px;
              background-image: url(@/assets/images/home/Zyn.png);
              .share-count {
                position: absolute;
                height: 12px;
                flex: 0 0 26px;
                width: 26px;
                font-size: 12px;
                left: 35px;
                top: 12px;
                font-weight: 600;
              }
            }
          }
        }
      }
      .play-control {
        position: absolute;
        bottom: 80px;
        left: 10px;
        z-index: 8;
        display: flex;
        align-items: center;
        color: #fff;
        .play-btn {
          width: 25px;
          height: 25px;
          border-radius: 999px;
          margin-right: 10px;
          font-size: 25px;
          z-index: 25;
        }
        .progress {
          width: 220px;
          height: 8px;
          background-color: rgb(238, 238, 238);
          border-radius: 8px;
          margin: 0 10px;
          position: relative;
          .layer {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: red;
            opacity: 0;
            z-index: 20;
          }
          .progress-btn {
            width: 12px;
            height: 150%;
            border-radius: 999px;
            background-color: rgb(250, 224, 16);
            position: absolute;
            left: calc(10% - 6px);
            top: -25%;
          }
          .progress-bar {
            width: 10%;
            height: 100%;
            background-color: rgb(250, 224, 16);
            position: absolute;
            border-radius: 8px;
          }
        }
      }
      ::v-deep .van-popup {
        position: absolute;
        bottom: 0;
        left: 0;
      }
      ::v-deep .van-overlay {
        background-color: rgba(0, 0, 0, 0);
      }
    }
  }
}
</style>